package cn.vonce.validator.config;

import cn.vonce.validator.intercept.ValidatorInterceptor;
import org.noear.solon.annotation.Controller;
import org.noear.solon.core.BeanBuilder;
import org.noear.solon.core.BeanWrap;

import java.lang.annotation.Annotation;

/**
 * 自动配置字段验证器
 *
 * @author Jovi
 * @version 1.0
 * @email imjovi@qq.com
 * @date 2025年07月26日02:12
 */
public class ValidatorAutoConfig implements BeanBuilder {

    @Override
    public void doBuild(Class clz, BeanWrap bw, Annotation anno) {
        ValidatorInterceptor validatorInterceptor = bw.context().getBean(ValidatorInterceptor.class);
        if (validatorInterceptor == null) {
            validatorInterceptor = new ValidatorInterceptor();
            BeanWrap beanWrap = bw.context().wrap("validatorInterceptor", validatorInterceptor);
            bw.context().putWrap("validatorInterceptor", beanWrap);
        }
        //全局自动配置
        if (anno.annotationType() == EnableValidatorAutoConfig.class) {
            EnableValidatorAutoConfig enableValidatorAutoConfig = (EnableValidatorAutoConfig) anno;
            bw.context().beanInterceptorAdd(Controller.class, validatorInterceptor);
            ResultConfig resultConfig = new ResultConfig();
            resultConfig.setResultType(enableValidatorAutoConfig.resultType());
            BeanWrap beanWrap = bw.context().wrap("resultConfig", resultConfig);
            bw.context().putWrap("resultConfig", beanWrap);
            bw.context().putWrap(ResultConfig.class, beanWrap);
        }
        //单个Controller配置
        else if (anno.annotationType() == EnableValidator.class) {
            bw.context().beanInterceptorAdd(EnableValidator.class, validatorInterceptor);
        }
    }


}
